<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        input {
            margin-top: 10px;
            margin-left: 10px;
        }

        #dv {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            margin-top: 10px;
        }
    </style>
</head>
<body>
<input type="button" value="400" id="btn1">
<input type="button" value="800" id="btn2">
<div id="dv"></div>

<script>
    function getById(id) {
        return document.getElementById(id);
    }

    getById('btn1').onclick = function () {
        animate(getById('dv'), 400, 10);
    };
    getById('btn2').onclick = function () {
        animate(getById('dv'), 800, 10);
    };

    function animate(elem, target, step=10) {
        clearInterval(elem.timeId);
        elem.timeId = setInterval(function () {
            var current = elem.offsetLeft;
            step = current < target ? Math.abs(step) : -Math.abs(step);
            current += step;
            //console.log(current);
            if (Math.abs(target - current) > Math.abs(step)) {
                elem.style.left = current + 'px';
            } else {
                clearInterval(elem.timeId);
                elem.style.left = target + 'px';
            }
        }, 50);

    }
</script>
</body>
</html>